<template>
    <div class="main">
        <div class="top">
            <img class="avatar" :src="`${config.downloadUrl}?name=${userStore.avator}`">
            <div class="user-info">
                <div style="display: flex;flex-direction: row;align-items: center;">
                    <span class="username">{{ userStore.username }}</span>
                    <el-tooltip class="box-item" effect="dark" content="点击修改个人信息" placement="bottom">
                        <el-icon @click="editUserMessage()" style="margin-left: 10px;cursor: pointer;">
                            <Edit />
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="点击修改密码" placement="bottom">
                        <el-icon style="margin-left: 10px;cursor: pointer;" @click="updatePassword()"><EditPen /></el-icon>
                    </el-tooltip>
                </div>
                <span class="email">邮箱:{{ userStore.email }}</span>
                <span class="email">签名:{{ userStore.introduction }}</span>
                <span @click="getuserFollowIds()" style="cursor: pointer;" class="email">关注:{{ userStore.follow
                }}</span>
                <span style="cursor: pointer;" class="email">粉丝:{{ userStore.fans }}</span>
                <button @click="toCreateArticle()" class="Btn">
                    <div class="sign">+</div>
                    <div class="text">new</div>
                </button>
            </div>
        </div>
        <div class="main-body">
            <el-tabs v-model="activeName" class="demo-tabs" type="card">
                <el-tab-pane label="已发布" name="first">
                    <publish v-if="activeName === 'first'" />
                </el-tab-pane>
                <el-tab-pane label="草稿箱" name="second">
                    <drafts v-if="activeName === 'second'" />
                </el-tab-pane>
                <el-tab-pane label="私有文章" name="third">
                    <privates v-if="activeName === 'third'" />
                </el-tab-pane>
                <el-tab-pane label="审核中" name="process">
                    <process v-if="activeName === 'process'" />
                </el-tab-pane>
                <el-tab-pane label="邀请协作" name="together">
                    <together v-if="activeName === 'together'" />
                </el-tab-pane>
                <el-tab-pane label="我的协作" name="together1">
                    <together1 v-if="activeName === 'together1'" />
                </el-tab-pane>
                <el-tab-pane label="我的点赞" name="like">
                    <like v-if="activeName === 'like'" />
                </el-tab-pane>
                <el-tab-pane label="我的收藏" name="favourite">
                    <favourite v-if="activeName === 'favourite'" />
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 修改信息 -->
        <el-dialog v-model="dialogFormVisible" title="修改信息" width="500">
            <el-form :model="form">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="form.username" autocomplete="off" />
                </el-form-item>
                <el-form-item label="签名" :label-width="formLabelWidth">
                    <el-input v-model="form.introduction" autocomplete="off" />
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input type="email" v-model="form.email" autocomplete="off" />
                </el-form-item>
                <el-form-item label="头像" :label-width="formLabelWidth">
                    <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="update()">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 修改密码 -->
        <el-dialog v-model="dialogPassword" title="修改信息" width="500">
            <el-form>
                <el-form-item label="旧密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="oldpassword" autocomplete="off" />
                </el-form-item>
                <el-form-item label="新密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="重新输入新密码" :label-width="formLabelWidth">
                    <el-input type="password" v-model="comparePassword" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateUserpassword()">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <ditials v-if="articleStore.isOpen" />
    <user-follow v-if="userStore.isFollowListOpen" />
    <datails v-if="articleStore.isForyouShow" />
    <favourite-datils v-if="articleStore.isFavouriteShow" />
    <likedatils v-if="articleStore.isLikeshow" />
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getByUserName } from '../../api/login'
import { userFollow, userFollowee, getuserMessage, updateUser, updateUserPassword } from '../../api/user'
import { useUserStore } from '../../stores/user'
import config from '../../../public/config'
import publish from './components/publish.vue'
import drafts from './components/drafts.vue'
import privates from './components/private.vue'
import process from './components/process.vue'
import { ElNotification } from 'element-plus'
import router from '../../router'
import ditials from './draw/ditials.vue'
import { useArticleStore } from '../../stores/article'
import { getUserFollowId } from '../../api/userFollow'
import UserFollow from './components/UserFollow.vue'
import together from './components/together.vue'
import together1 from './components/together1.vue'
import datails from './components/datails.vue'
import like from './components/like.vue'
import favourite from './components/favourite.vue'
import favouriteDatils from './draw/favouriteDatils.vue'
import likedatils from './draw/likeDatils.vue'



const activeName = ref('first')
const userStore = new useUserStore()
const articleStore = new useArticleStore()
const dialogFormVisible = ref(false)
const dialogPassword=ref(false)
let actionUrl = config.uploadUrl
let imageUrl = ref('')
const form = reactive({
    id: localStorage.getItem("userId"),
    username: '',
    introduction: '',
    email: '',
    avatar: ''
})

const password= ref('')
const oldpassword=ref('')
const comparePassword=ref('')
onMounted(() => {
    getUserMessage()
    getUserFollow()
    getUserFollowee()
})

async function getUserMessage() {
    let params = new URLSearchParams();
    params.append("username", localStorage.getItem("username"))
    await getByUserName(params)
        .then(res => {
            if (res.code == 200) {
                userStore.username = res.data.username
                userStore.id = res.data.id
                userStore.avator = res.data.avatar
                userStore.email = res.data.email
                userStore.introduction = res.data.introduction
                form.avatar = res.data.avatar
                form.username = res.data.username
                form.email = res.data.email
                form.introduction = res.data.introduction
                imageUrl.value = `${config.downloadUrl}?name=${res.data.avatar}`
            } else if (res.code == 400) {
                ElNotification({
                    title: '请求失败',
                    message: res.message,
                    type: 'error',
                    showClose: false,
                });
            }
        })
}
function toCreateArticle() {
    router.push('/article')
}

async function getUserFollow() {
    let params = new URLSearchParams()
    params.append("followerId", localStorage.getItem("userId"))
    await userFollow(params)
        .then(res => {
            userStore.follow = res.data
        })
}
async function getUserFollowee() {
    let params = new URLSearchParams()
    params.append("followeeId", localStorage.getItem("userId"))
    await userFollowee(params)
        .then(res => {
            userStore.fans = res.data
        })
}
async function getuserFollowIds() {
    let params = new URLSearchParams()
    params.append("followerId", localStorage.getItem("userId"))
    await getUserFollowId(params).then(res => {
        if (res.code === 200) {
            const followeeIds = res.data.map(item => item.followeeId);
            Promise.all(followeeIds.map(id => getuserMessage({ id })))
                .then(responses => {
                    userStore.FollowList = responses.map(res => res.data);
                    userStore.isFollowListOpen = true
                })
                .catch(error => {
                    console.error("获取用户信息失败", error);
                });
        }
    })
}
function editUserMessage() {
    dialogFormVisible.value = true
    getUserMessage()
}
async function update() {
    // 邮箱格式验证
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(form.email)) {
        ElNotification({
            title: '注意',
            message: '您输入的邮箱格式不正确请检查',
            type: 'warning',
            showClose: false,
        });
        return;
    }
    await updateUser(form).then(res => {
        if (res.code === 200) {

            ElNotification({
                title: '成功',
                message: res.message,
                type: 'success',
                showClose: false,
            });
            dialogFormVisible.value = false
            getUserMessage()
        } else {
            ElNotification({
                title: '注意',
                message: res.message,
                type: 'warning',
                showClose: false,
            });
        }

    })
}
//图片上传成功后的方法
function handleAvatarSuccess(response, file, fileList) {
    imageUrl.value = `${config.downloadUrl}?name=${response.data}`
    form.avatar = response.data
}
//上传图片之前
function beforeUpload(file) {
    if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
            ElMessage({
                type: 'info',
                message: '上传图片只支持 png、jpeg、jpg 格式！',
            })
            // this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
            // this.$refs.upload.clearFiles()
            return false
        }
        if (!size) {
            ElMessage({
                type: 'info',
                message: '上传文件大小不能超过 2MB!',
            })
            // this.$message.error('上传文件大小不能超过 2MB!')
            return false
        }
        return file
    }
}
function updatePassword(){
    dialogPassword.value=true
}
async function updateUserpassword() {
    const id = localStorage.getItem("userId");
    if (!id) {
        ElNotification({
            title: '错误',
            message: '用户未登录',
            type: 'error',
            showClose: false,
        });
        return;
    }

    if (!password.value || !comparePassword.value) {
        ElNotification({
            title: '注意',
            message: '密码不能为空',
            type: 'warning',
            showClose: false,
        });
        return;
    }

    if (password.value !== comparePassword.value) {
        ElNotification({
            title: '注意',
            message: '新密码不一致，请重新输入',
            type: 'warning',
            showClose: false,
        });
        return;
    }

    
    const data = new URLSearchParams
    data.append('id',id)
    data.append('oldPassword',oldpassword.value)
    data.append('newPassword',password.value)
    try {
        const res = await updateUserPassword(data);
        if (res.code === 200) {
            localStorage.removeItem("username");
            localStorage.removeItem("token");
            localStorage.removeItem("tokenExpiry");
            localStorage.removeItem("userId");
            router.push('/');
            ElNotification({
                title: '成功',
                message: '修改成功，请重新登录',
                type: 'success',
                showClose: false,
            });
        } else {
            ElNotification({
                title: '注意',
                message: res.message,  
                type: 'warning',
                showClose: false,
            });
        }
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '请求失败，请稍后重试',
            type: 'error',
            showClose: false,
        });
        console.error('更新密码失败:', error);
    }
}

</script>

<style scoped>
.main {
    width: 100%;
    height: 98vh;
    display: flex;
    flex-direction: column;
}

.top {
    background-color: #f5f5f5;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
}

.main-body {
    width: 100%;
    height: 80%;
    margin-top: 30px;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    border: 2px solid #007bff;
    margin-right: 20px;
}

.user-info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    font-size: 20px;
    font-weight: 600;
}

.username {
    color: #333;
    font-size: 24px;
}

.email {
    margin-top: 5px;
    color: #666;
}

/* From Uiverse.io by Yaya12085 */
.Btn {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 45px;
    height: 45px;
    border-radius: calc(45px/2);
    border: none;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition-duration: .3s;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.199);
    background: linear-gradient(144deg, #af40ff, #5b42f3 50%, #00ddeb);
    margin-top: 5px;
}

/* plus sign */
.sign {
    width: 100%;
    font-size: 2.2em;
    color: white;
    transition-duration: .3s;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* text */
.text {
    position: absolute;
    right: 0%;
    width: 0%;
    opacity: 0;
    color: white;
    font-size: 1.4em;
    font-weight: 500;
    transition-duration: .3s;
}

/* hover effect on button width */
.Btn:hover {
    width: 125px;
    transition-duration: .3s;
}

.Btn:hover .sign {
    width: 30%;
    transition-duration: .3s;
    padding-left: 15px;
}

/* hover effect button's text */
.Btn:hover .text {
    opacity: 1;
    width: 70%;
    transition-duration: .3s;
    padding-right: 15px;
}

/* button click effect*/
.Btn:active {
    transform: translate(2px, 2px);
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>